import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.ImageIcon;


/**
 * VideoStreamListener 
 * Listens to the the server for messages containing images
 * from the camera. This creates a stream of images that form
 * video. Constantly updating the GUI with each new image.
 * @author Torbjorn Elebjork							
 */
public class VideoStreamListener extends Thread {
	Boolean run;
	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
 	GUIMain guiMain;
 	ImageIcon imageIcon;
 	
	/**
	 * The constructor creates a socket for the video stream.
	 * @param ip The ip-address to the server
	 * @param port The port the socket communication through
	 */
 	VideoStreamListener(String ip, int port,GUIMain guiMain){
		this.guiMain = guiMain;
		run=true;
		try{
			requestSocket = new Socket(ip, port);
			System.out.println("VideoStreamListener is connected to " + ip + " on port " + port);
		}
		catch(UnknownHostException unknownHost){
			System.err.println("Trying to connect to an unknown host.");
		}
		catch(IOException ioException){
			System.out.println("Could not create requestSocket: " + ioException );
			System.out.println("Print Stack Trace: ");
			ioException.printStackTrace();
		}	
	}
	
	/**
	 * Starts the VideoStreamListener thread. 
	 * Listens to messages containing images
	 * of the video stream and updates the GUI with the new image.
	 */
	public void run(){
		try{
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			try{
				do{
					imageIcon = (ImageIcon)in.readObject();
					guiMain.setCameraImage(imageIcon);	
				} while(run);	 
			}
			catch(ClassNotFoundException classNot){
				System.err.println("Recieved data has invalid format.");
			}	
		}
		catch(IOException ioException){
			System.out.println("Could not create input/output streams:" + ioException );
			System.out.println("Print Stack Trace 2: ");
			ioException.printStackTrace();
		}
		finally{		
			try{
				//Closing connection
				//guiMain.setCurrentServerIPTextbox("Disconnected");
				in.close();
				out.close();
				requestSocket.close();
				System.out.println("Socket successfully closed");
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}
	
	/**
	 * Terminates the video stream thread.
	 * @param setRun
	 */
	void setRun(Boolean setRun){
		run = setRun;
	}
}
